/**
 * 保存到本地并自动点击
 * @param data
 * @param name
 */
const saveAs = (data, name) => {
  const urlObject = window.URL || window.webkitURL || window
  const exportBlob = new Blob([data])
  const saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
  saveLink.href = urlObject.createObjectURL(exportBlob)
  saveLink.download = name
  saveLink.click()
}

/**
 * 下载含有url的文件
 * @param url 网络文件地址
 * @param fileName 文件名
 */
export const downloadUrlFile = (url, fileName) => {
  const url2 = url.replace(/\\/g, '/')
  const xhr = new XMLHttpRequest()
  xhr.open('GET', url2, true)
  xhr.responseType = 'blob'
  // 为了避免大文件影响用户体验，建议加loading
  xhr.onload = () => {
    if (xhr.status === 200) {
      // 获取文件blob数据并保存
      saveAs(xhr.response, fileName)
    }
  }
  xhr.send()
}
